<?php

namespace app\admin\controller;

use app\admin\model\Admin;
use app\common\controller\Backend;
use app\common\model\Hospital;
use app\common\model\User;
use Exception;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 故障单管理
 *
 * @icon fa fa-circle-o
 */
class Fault extends Backend
{

    /**
     * Fault模型对象
     * @var \app\common\model\Fault
     */
    protected $model = null;
    protected $Ids = null;
    protected $user = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Fault;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->Ids=$this->auth->getGroupIds();
        $this->user=$this->auth->getUserInfo();
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $filter = $this->request->request("filter");
            $filter=json_decode($filter,true);
            $where1="1=1";
            if(array_key_exists("department_name",$filter)){
                $op = json_decode($this->request->request("op"),true);
                $where1="department.name like '%".$filter["department_name"]."%'";
                unset($op["department_name"]);
                unset($filter["department_name"]);
                $this->request->get(["filter"=>json_encode($filter),'op'=>json_encode($op)]);
                list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            }else{
                list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            }
            $where2="1=1";
            if($this->Ids[0]==2) {
                $admin = Admin::get($this->user["id"]);
                if ($admin) {
                    $where2 = ["account" => $admin["username"]];
                    $hospital = Hospital::field("id")->where(["status" => 1])
                        ->where('FIND_IN_SET("' . $this->user["id"] . '", admin_ids)')->find();
                    $where2=["department.hospital_id"=>$hospital["id"]];
                }
            }
            /**/
            /*list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $where=new \ReflectionFunction($where);
            $where=$where->getStaticVariables();
            foreach ($where["where"] as $k=>$v){
                if($v[0]=="fault.department_name"){
                    unset($where["where"][$k]);
                }
            }*/
            $list = $this->model
                    ->with(['equipment'])
                    ->field("department.id department_id,department.name department_name,hospital.name 'hospital.name'")
                    ->join("department department","department.id=equipment.department_id","left")
                    ->join("hospital hospital","department.hospital_id=hospital.id","left")
                    ->where($where)
                    ->where($where1)
                    ->where($where2)
                    ->order($sort, $order)
                    ->paginate($limit);
            foreach ($list as $row) {
                $row->getRelation('equipment')->visible(['name','marking','serial','images','software_version','enclosure']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     *问题描述
     * */
    public function problem($ids){
        $row=$this->model->field("problem,images")->where(["id"=>$ids])->find();
        if($row && !empty($row["images"])){
            $row["images"]=explode(",",$row["images"]);
        }
        $this->assign("row",$row);
        return $this->view->fetch();
    }
    /**
     * 审核
     * */
    public function operation(){
        if (!$this->request->param("ids")) $this->error('id为空');
        $param=$this->request->param();
        $row = $this->model->get($param["ids"]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Db::startTrans();
        try {
            if($param["status"]==1){
                //已处理
                \app\common\model\Equipment::where(["id"=>$row["equipment_id"]])->update(["status"=>1]);
            }
            $result = $row->allowField(true)->save($param);
            Db::commit();
        } catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result !== false) {
            $this->success();
        } else {
            $this->error(__('No rows were updated'));
        }
    }
}
